package br.com.engine.input;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;

import br.com.engine.controle.Tela;

public class KeyBoardAdapter extends KeyAdapter
{
	private Map<Integer, Action> eventsPressed  = new HashMap<Integer, Action>( );
	private Map<Integer, Action> eventsReleased = new HashMap<Integer, Action>( );
	
	private KeyBoardAdapter( ) { }
	
	/* (non-Javadoc)
	 * @see java.awt.event.KeyAdapter#keyPressed(java.awt.event.KeyEvent)
	 */
	public void keyPressed( KeyEvent e ) 
	{
		if( eventsPressed.containsKey( e.getKeyCode( ) ) )
		{
			Action action = eventsPressed.get( e.getKeyCode( ) );
			
			EventoTecla evento = new EventoTecla( );
			evento.setKeyCode( e.getKeyCode( ) );
			evento.setTimeDispared( System.currentTimeMillis( ) );
			
			action.executa( evento );
		}
	}
	
	@Override
	public void keyReleased( KeyEvent e ) 
	{
		if( eventsReleased.containsKey( e.getKeyCode( ) ) )
		{
			Action action = eventsReleased.get( e.getKeyCode( ) );
			
			EventoTecla evento = new EventoTecla( );
			evento.setKeyCode( e.getKeyCode( ) );
			evento.setTimeDispared( System.currentTimeMillis( ) );
			
			action.executa( evento );
		}
	}
	
	public void addkeyTiger( KeyMap key, boolean isPressed, Action action ) 
	{
		if( isPressed )
			eventsPressed.put( key.getKey( ), action );
		else
			eventsReleased.put( key.getKey( ), action );
	}
	
	public void addkeysTiger( Action action, boolean isPressed, KeyMap... keys ) 
	{
		if( isPressed )
		{
			for( KeyMap key : keys ) 
			{
				eventsPressed.put( key.getKey( ), action );
			}
		}
		else
		{
			for( KeyMap key : keys )
			{	
				eventsReleased.put( key.getKey( ), action );
			}
		}
	}
	
	public static KeyBoardAdapter infNewInstacia( )
	{
		KeyBoardAdapter tecladoAdapter = new KeyBoardAdapter( );
		
		Tela.getTela( ).addKeyListener( tecladoAdapter );
		
		return tecladoAdapter;
	}
}